define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'fastflowbase'], function ($, undefined, Backend, Table, Form, FastflowBase) {
    var tableBill = $("#table-bill");
    var tableList = $("#table-list");
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init();
            this.table.bill();
            this.table.list();
            $('.today-carbon-jump').click(function () {
                tableList.bootstrapTable('refreshOptions', []);
                $('input[name="id"]').val($(this).data('id'));
                $("#box-list button[type='submit']").trigger("click");
            });
            $('.fastflow-unread-btn').click(function (e) {
                tableList.bootstrapTable('refreshOptions', []);
                $('select[name="is_read"]').val(0);
                $("#box-list button[type='submit']").trigger("click");
            });
            $('.fastflow-read-btn').click(function (e) {
                tableList.bootstrapTable('refreshOptions', []);
                $('select[name="is_read"]').val(1);
                $("#box-list button[type='submit']").trigger("click");
            });
            $('.fastflow-today-btn').click(function (e) {
                tableList.bootstrapTable('refreshOptions', []);
                $('input[name="sendtime"]').val($(this).data('range'));
                $("#box-list button[type='submit']").trigger("click");
            });
            $('.fastflow-all-btn').click(function (e) {
                $("#box-list button[type='reset']").trigger("click");
            });
            tableList.on('post-body.bs.table', function (e, data) {
                FastflowBase.api.renderbadge();
            });
        },
        table: {
            bill: function () {
                tableBill.bootstrapTable({
                    url: 'fastflow/carbon/bill',
                    toolbar: '#toolbar-bill',
                    sortName: 'id',
                    search: false,
                    showExport: false,
                    pageList: [10],
                    pageSize: 10,
                    showToggle: false,
                    singleSelect: true,
                    showColumns: false,
                    columns: [
                        [
                            {
                                field: 'id', formatter: function (value, row, index) {
                                    return '<i class="fa fa-file-text text-gray"></i>';
                                }
                            },
                            {
                                field: 'bill_name', title: __('Bill_name'), formatter: function (value, row, index) {
                                    return '<span class="text-bold" style="color: #0a5ba6" data-toggle="tooltip" data-placement="top" title="" data-original-title="点击筛选">' + value + '</span>';
                                }
                            },
                            {
                                field: 'carbons',
                                title: __('未读抄送'),
                                width: 100,
                                formatter: function (value, row, index) {
                                    if (value == 0) {
                                        return '';
                                    } else {
                                        return '<small class="badge bg-red">' + value + '</small>'
                                    }
                                }
                            },
                        ]
                    ]
                });

                // 为表格1绑定事件
                Table.api.bindevent(tableBill);
                tableBill.on('click-row.bs.table', function (e, row, ele) {
                    $('.row-active').removeClass('row-active');
                    $(ele).addClass('row-active');
                    tableList.bootstrapTable('refreshOptions', []);
                    $("#box-list .form-commonsearch input[name='bill']").val(row['bill_table']);
                    $("#box-list button[type='submit']").trigger("click");
                });
            },
            list: function () {
                tableList.bootstrapTable({
                    url: 'fastflow/carbon/index',
                    extend: {
                        index_url: 'fastflow/carbon/index' + location.search,
                        del_url: 'fastflow/carbon/del',
                        multi_url: 'fastflow/carbon/multi',
                        table: 'fastflow_carbon',
                    },
                    toolbar: '#toolbar-list',
                    sortName: 'sendtime',
                    search: false,
                    sortOrder: 'desc',
                    pageSize: 10,
                    showToggle: false,
                    searchFormVisible: true,
                    columns: [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('ID')},
                            {field: 'sender_name', title: __('Sender_name'), operate: false},
                            {field: 'bill_name', title: __('Bill_name'), operate: false,},
                            {field: 'bill', title: __('Bill'), visible: false},
                            {
                                field: 'bill_id', title: __('Bill_id'), formatter: function (value, row, index) {
                                    if (row['bill_row_title'] != '') {
                                        return value + '(' + row['bill_row_title'] + ')';
                                    } else {
                                        return value;
                                    }
                                }
                            },
                            {field: 'sender_id', title: __('Sender_id'), visible: false},
                            {
                                field: 'sendtime',
                                title: __('Sendtime'),
                                operate: 'RANGE',
                                addclass: 'datetimerange',
                                autocomplete: false
                            },
                            {
                                field: 'is_read',
                                title: __('Is_read'),
                                searchList: {"0": __('Is_read 0'), "1": __('Is_read 1')},
                                formatter: Table.api.formatter.label,
                                custom: {'0': 'danger', '1': 'success'}
                            },
                            {
                                field: '',
                                title: __('View'),
                                operate: false,
                                table: tableList,
                                events: Controller.api.events.detail,
                                formatter: Controller.api.formatter.detail
                            },
                            {
                                field: 'operate',
                                title: __('Operate'),
                                table: tableList,
                                events: Table.api.events.operate,
                                formatter: Table.api.formatter.operate
                            },
                        ]
                    ]
                });

                // 为表格2绑定事件
				Table.api.bindevent(tableList);
                tableList.on('load-success.bs.table', function (e, data) {
                    $("#fastflow-all").text(data.extend.all);
                    $("#fastflow-unread").text(data.extend.unread);
                    $("#fastflow-read").text(data.extend.read);
                });
                $('.btn-display-all').on('click', function (e) {
                    $("#box-list button[type='reset']").trigger("click");
                });
                tableList.on('dbl-click-row.bs.table', function (e, row, element, field) {
                    $('.btn-detail', element).trigger("click");
                });
            }
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            //调整窗口大小---
            var footer = $('.footer');
            $('.layui-layer-content', parent.document).after(footer);
            footer.css('display', 'block');
            var dialogHeight = $('.layui-layer-iframe', parent.document).height();
            $('.layui-layer-iframe', parent.document).height(dialogHeight - 53);
            var iframeHeight = $('.layui-layer-content iframe', parent.document).height();
            $('.layui-layer-content iframe', parent.document).height(iframeHeight - 53);
            $('.layui-layer-resize', parent.document).css('bottom', '-53px');
            //---调整窗口大小

            Controller.api.bindPrintEvent();
            //不放在bindPrintEvent方法内，防止反复弹出打印页
            $('.bill-print', parent.document).click(function () {
                Controller.api.print('bill');
            });
            $('.merge-print', parent.document).click(function () {
                Controller.api.mergePrint();
            });
            $('.export-word', parent.document).click(function () {
                Controller.api.exportWord();
            });

            let index = layer.load();
            $.ajax({
                type: "get",
                url: Config.controller_url + "/edit",
                data: {ids: Config.bill_id, way: 'detail'},
                success: function (data) {
                    if ($('#edit-form', data).length == 0) {
                        $('.alert').removeClass('hidden');
                    }
                    $('#fastflow-right-content #bill-edit').append($('#edit-form', data));
                    $('[name^="row"]', $('#edit-form', '#fastflow-right-content')).attr('disabled', 'disabled');
                    $('button', $('#edit-form', '#fastflow-right-content')).addClass('hidden');
                    Form.api.bindevent($("#edit-form"));
                    $('a.btn', $('#edit-form', '#fastflow-right-content')).addClass('hidden');
                    layer.close(index);
                },
                error: function (e) {
                    layer.close(index);
                }
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            bindPrintEvent: function () {
                $('.table-print').click(function () {
                    Controller.api.print('table');
                });
                $('.timeline-print').click(function () {
                    Controller.api.print('timeline');
                });
            },
            print: function (type) {
                $('.' + type + '-print').addClass('hidden');
                if (type === 'table' || type === 'timeline') {
                    $('.detail-table').css('table-layout', 'unset');
                    //提取资料地址
                    var fileSpan = $('.flow-file', $('.' + type));
                    $(fileSpan).each(function (index, item) {
                        var fileUrl = $('a', $(item)).attr('href');
                        var fileName = $('a', $(item)).html();
                        $(item).html("<label data-name='" + fileName + "'>" + Config.domain + "<span>" + fileUrl + "</span>" + "</label>");
                    });
                }
                if (type == 'bill') {
                    $('.bill-legend').removeClass('hidden');
                }
                var html = $('body', window.document).html();
                var printStart = "<!--" + type + "PrintStart-->";
                var printEnd = "<!--" + type + "PrintEnd-->";
                var printHtml = html.substr(html.indexOf(printStart));
                printHtml = printHtml.substring(0, printHtml.indexOf(printEnd));
                window.document.body.innerHTML = printHtml;
                window.print();
                window.document.body.innerHTML = html;
                if (type === 'table' || type === 'timeline') {
                    $('.detail-table').css('table-layout', 'fixed');
                    //还原资料下载按钮
                    var fileSpan = $('.flow-file', $('.' + type));

                    $(fileSpan).each(function (index, item) {
                        var fileLable = $('label', $(item));
                        var fileName = fileLable.data('name');
                        var fileUrl = $('span', fileLable).html();
                        $(item).html("<a href='" + fileUrl + "' class='btn btn-info-light btn-xs'>" + fileName + "</a>");
                    });

                }
                $('.' + type + '-print').removeClass('hidden');
                $('.bill-legend').addClass('hidden');
                Controller.api.bindPrintEvent();
            },
            mergePrint: function () {
                $('.table-print').addClass('hidden');
                $('.detail-table').css('table-layout', 'unset');
                //提取资料地址
                var fileSpan = $('.flow-file', $('.table'));
                $(fileSpan).each(function (index, item) {
                    var fileUrl = $('a', $(item)).attr('href');
                    var fileName = $('a', $(item)).html();
                    $(item).html("<label data-name='" + fileName + "'>" + Config.domain + "<span>" + fileUrl + "</span>" + "</label>");
                });

                var html = $('body', window.document).html();
                //table
                var tableStart = "<!--tablePrintStart-->";
                var tableEnd = "<!--tablePrintEnd-->";
                var tableHtml = html.substr(html.indexOf(tableStart));
                tableHtml = tableHtml.substring(0, tableHtml.indexOf(tableEnd));
                //bill
                var billStart = "<!--billPrintStart-->";
                var billEnd = "<!--billPrintEnd-->";
                var billHtml = html.substr(html.indexOf(billStart));
                billHtml = billHtml.substring(0, billHtml.indexOf(billEnd));

                window.document.body.innerHTML = tableHtml + billHtml;
                window.print();
                //还原
                window.document.body.innerHTML = html;
                $('.detail-table').css('table-layout', 'fixed');
                //还原资料下载按钮
                var fileSpan = $('.flow-file', $('.table'));

                $(fileSpan).each(function (index, item) {
                    var fileLable = $('label', $(item));
                    var fileName = fileLable.data('name');
                    var fileUrl = $('span', fileLable).html();
                    $(item).html("<a href='" + fileUrl + "' class='btn btn-info-light btn-xs'>" + fileName + "</a>");
                });
                $('.table-print').removeClass('hidden');
                Controller.api.bindPrintEvent();
            },
            exportWord: function () {
                $.ajax({
                    type: "get",
                    url: "fastflow/carbon/exportWord",
                    data: {
                        carbon_id: Config.carbon_id,
                        bill: Config.bill,
                        bill_id: Config.bill_id
                    },
                    success: function (data) {
                        if (data['code'] == 1) {
                            let url = data['data']['url'];
                            let a = document.createElement('a');
                            a.href = url;
                            a.download = 'detail_table.docx';
                            a.click();
                            delete a;
                        } else if (data['code'] == 0) {
                            Toastr.error(data['msg']);
                        }
                    },
                    error: function (e) {
                    }
                });
            },
            formatter: {
                detail: function (value, row, index) {
                    html = '<a href="fastflow/carbon/detail?id=' + row['id'] + '" class="btn btn-xs btn-success btn-dialog btn-detail" data-area=["80%","90%"] title="查阅"><i class="fa fa-envelope"></i></a>';
                    return html;
                },
            },
            events: {
                detail: {
                    'click .btn-detail': function (e, value, row, index) {
                        e.stopPropagation();
                        e.preventDefault();
                        var table = $("#table-bill");
                        var options = table.bootstrapTable('getOptions');
                        var ids = row[options.pk];
                        row = $.extend({}, row ? row : {}, {ids: ids});
                        Fast.api.open(Table.api.replaceurl($(this).attr('href'), row, table), $(this).data("original-title") || $(this).attr("title"), $(this).data() || {});
                        if (row['is_read'] == 0) {
                            setTimeout(function (e) {
                                $("#box-list .btn-refresh").trigger("click")
                                tableBill.bootstrapTable('refresh');
                                FastflowBase.api.renderbadge();
                            }, 1000);
                        }
                    },
                },
            },
        }
    };
    return Controller;
});
